<h1 class="text-center"><?php echo __("Quotazioni"); ?></h1>

    <form>
          <input type="hidden" id="country" name="country" value="<?php echo $country; ?>" />
          <input type="hidden" id="match" name="match" value="<?php echo $match; ?>" />
	</form>
		
          <div id="webroot" data-url='<?php echo $this->webroot; ?>' ></div>
          
                <div id="tournament-template" class="tournament hidden container-fluid">
                        <div class="header-tournament-live row">
                            <div class="country col-md-12"></div>
                        </div>
                        <div class="body-tournament-live row"></div>
                </div>
                <div id="match-template" class="match hidden container-fluid" data-static-id="">
                        <div class="header-match-live row">
                            <div class="time col-md-2"></div>
                            <div class="localteam text-right col-md-3"><a class="team-popover"></a></div>
                            <div class="score col-md-2"></div>
                            <div class="visitorteam text-left col-md-3"><a class="team-popover"></a></div>
                            <div class="date col-md-2"></div>
                        </div>
                        <div class="body-match-live" style="display:none;"></div>
                </div>
                <div id="event-template" class="event hidden">
                </div>
                <div id="event-row-template" class="event-row row">
                  <div class="tdMinute col-md-2"><i class="fa-time"></i></div>
                  <div class="tdlocalteam col-md-3"></div>
                  <div class="tdScore col-md-2"></div>
                  <div class="tdvisitorteam col-md-3"></div>
                  <div class="empty col-md-2"></div>
                </div>
                <table id="lineups-template" class="table table-hover hidden">
                      <thead>
                        <tr>
                          <th><?php echo __("Numero"); ?></th>
                          <th><?php echo __("Giocatore"); ?></th>
                        </tr>
                      </thead>
                      <tbody>
                            <tr id="lineups-row-template"><td class="lineups-number"></td><td class="lineups-player"></td></tr>
                      </tbody>
                </table>  

                <div id="odds-template" class="odds hidden"></div>
                
              <div id="odds-type-tamplate" class="odds-type row hidden">
	          	<div class="col-md-12">
		           <!-- Nav tabs -->
		            <ul class="nav nav-tabs">
		              <li class="active 3wayresult"><a href="#3wayresult" data-toggle="tab">3Way Result</a></li>
		              <li><a href="#homeaway" data-toggle="tab">Home/Away</a></li>
		              <li><a href="#overunder" data-toggle="tab">Over/Under</a></li>
		              <li><a href="#handicap" data-toggle="tab">Handicap</a></li>
		              <li><a href="#3WayResult1stHalf" data-toggle="tab">3Way Result 1st Half</a></li>
		              <li><a href="#OverUnder1stHalf" data-toggle="tab">Over/Under 1st Half</a></li>
		              <li><a href="#BothTeamstoScore" data-toggle="tab">Both Teams to Score</a></li>
		              <li><a href="#OverUnder2ndHalf" data-toggle="tab">Over/Under 2nd Half</a></li>
		              <li><a href="#DoubleChance" data-toggle="tab">Double Chance</a></li>
		              <li><a href="#TeamToScoreFirst" data-toggle="tab">Team To Score First</a></li>
		              <li><a href="#TeamToScoreLast" data-toggle="tab">Team To Score Last</a></li>
		              <li><a href="#3WayHandicap" data-toggle="tab">3Way Handicap</a></li>
		            </ul>
		            <!-- Tab panes -->
		            <div class="tab-content">
		              <div class="tab-pane fade in active 3wayresult" id="3wayresult"></div>
		              <div class="tab-pane fade in" id="homeaway"></div>
		            </div>
	             </div>
	          </div>

            <table id="odd-3wayresult-table-template" class="table table-striped odd-3wayresult hidden">
                  <thead>
                    <tr>
                      <th style="text-align: center;"><?php echo __("Bookmaker"); ?></th>
                      <th style="text-align: center;"><?php echo __("1"); ?></th>
                      <th style="text-align: center;"><?php echo __("X"); ?></th>
                      <th style="text-align: center;"><?php echo __("2"); ?></th>
                      <th style="text-align: center;"><?php echo __("Profitto"); ?></th>
                    </tr>
                  </thead>
                  <tbody>
			            <tr id="odd-3wayresult-row-template" class="hidden">
			            	<td class="bookmaker-name"></td>
			            	<td class="bookmaker-odd-1"></td>
			            	<td class="bookmaker-odd-X"></td>
			            	<td class="bookmaker-odd-2"></td>
			            	<td class="bookmaker-odd-profitto"></td>
			            </tr>
                  </tbody>
            </table>  

                <div id="tournaments" class="" data-country='<?php echo $country; ?>' ></div>


<script>

    // var countdown = new Countdown($('#countdown'),59,refresh);
    // var countdownTimer = $.timer(function() {countdown.execute();},1000,true);

    $(document).ready(function() {
        // var interval = 1000 * 20; // where X is your every X seconds
        refresh();
        // $('#start-stop').click(function(){
            // if ($('#start-stop').data('action')=='stop') {
                // countdownTimer.pause();
                // $('#start-stop').data('action','start');
            // } else {
                // countdownTimer.play();
                // $('#start-stop').data('action','stop');
            // }
        // });
        
        $(document).on('click', ".header-match-live", function() {
           $(this).next().slideToggle("fast");
        });

    });
    
    function refresh() {
    	  // console.log(nextCalendar);
          country = $('#tournaments').data('country');
          url = $('#webroot').data('url')+'Feed/getOdds/'+country+'_shedule';
    	  
          $.ajax({ type: "GET", url: url
                , dataType: "xml"
                , success: function(xml) {
                    //console.log('refresh');
                    $('#tournaments').empty();
                    $(xml).find('category').each(function() {
                        writeTournament($(this));
                    });
                    // aggiungo i commenti dove trovo le informazioni della formazione e le statistiche
                    // addCommentaries(country);
                }
                , error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
           });
    	  
    }

	function addCommentaries(country) {
            // recupero altre infomrazioni inerenti alla squadra per il match corrente
            $.ajax({ type: "GET", url: "<?php echo $this -> webroot; ?>Feed/getCommentaries/"+country
                , dataType: "json"
                , success: function(data) {
                    if(data.success) {
                          $.ajax({ type: "GET", url: data.url
                            , dataType: "xml"
                            , success: function(xml) {
                                console.log('getCommentaries');
                              $(xml).find('match').each(function() {
                                writeLineups($(this));
                              });
                            }
                            , error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
                          });
                    } else
                        setFlash(data.message, data.level);
                }
            });
	}    
    
    function lastMatchs(formatted_date) {
        var t_date = new Date(formatted_date.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
        var today=new Date();
        var ore = $("input[name='period']:checked").val();
        if (!$.isNumeric(ore))
        	ore = 0;
        var ventiquattroOre = 1000*60*60*ore;
        var yesterday=today.getTime() - ventiquattroOre;
        // console.log(yesterday + ' - ' + t_date.getTime());
        // console.log(yesterday <= t_date.getTime());
        return (yesterday <= t_date.getTime());
    }

    
    function writeTournament(tournament) {
            tournamentElement = $('#tournament-template').clone();
            HeaderTournamentElement = tournamentElement.children('.header-tournament-live');
            HeaderTournamentElement.children('.country').html(tournament.attr('name'));
            HeaderTournamentElement.children('.date').html(tournament.find('matches').attr('formatted_date'));
            tournament.find('match').each(function() {
            	if ($("#match").val().length===0 || ($("#match").val().length>0 && $("#match").val()==$(this).attr('static_id'))) {
					console.log("scrivi match");
                    tournamentElement.children('.body-tournament-live').append(writeMatch($(this)));
            	}
            });
            tournamentElement.removeAttr('id');
            tournamentElement.removeClass('hidden');
            tournamentElement.appendTo($('#tournaments'));
    }
    
    function writeMatch(match) {
        matchElement = $('#match-template').clone();
        matchElement.attr('id','match'+match.attr('static_id'));
        localteam = match.find('localteam');
        visitorteam = match.find('visitorteam');
        // console.log(match.attr('static_id'));
        matchElement.data('static-id', match.attr('static_id'));
        // console.log(matchElement.data('static-id'));
        matchElement.children('.header-match-live').children('.localteam').children('a').html(localteam.attr('name'));
        matchElement.children('.header-match-live').children('.score').html('[' + localteam.attr('goals') + ' - ' + visitorteam.attr('goals') + ']');
        matchElement.children('.header-match-live').children('.visitorteam').children('a').html(visitorteam.attr('name'));
        matchElement.children('.header-match-live').children('.time').html(match.attr('time') + ' (' + match.attr('status') + ')');
        matchElement.children('.header-match-live').children('.date').html(match.attr('formatted_date'));
        // eventElement = $('#event-template').clone();
        // match.find('event').each(function() {
            // writeEvent(eventElement,$(this));
        // });
        // matchElement.children('.body-match-live').append(eventElement);
        // eventElement.removeAttr('id');
        // eventElement.removeClass('hidden');
        // aggiungi odds -------------------------
        oddsElement = $('#odds-template').clone();
        match.find('odds').each(function() {
        	console.log("write odds");
            writeOdds(match.attr('static_id'), oddsElement, $(this));
        });
        oddsElement.removeAttr('id');
        oddsElement.removeClass('hidden');
        matchElement.children('.body-match-live').append(oddsElement);
        // ---------------------------------------
        // matchElement.removeAttr('id');
        matchElement.removeClass('hidden');
        return matchElement;
    }

    function writeEvent(eventElement, eventData) {
        // console.log(eventData);
        eventRowElement = $('#event-row-template').clone();
        // console.log(eventElement.find('tr').html());
        eventRowElement.children('.td'+eventData.attr('team')).html('<div class="'+eventData.attr('type')+" "+eventData.attr('team')+'"></div> ' + eventData.attr('player'));
        eventRowElement.children('.tdMinute').html("<i class='fa-clock-o'></i> "+eventData.attr('minute')+"'");
        eventRowElement.children('.tdScore').html(eventData.attr('result'));
        eventRowElement.removeAttr('id');
        eventRowElement.removeClass('hidden');
        eventElement.append(eventRowElement);
        // return eventElement;
    }
    
    function writeOdds(marchid, oddsElement, oddsData) {
    	// console.log(oddsData);	
        oddsTypeElement = $('#odds-type-tamplate').clone();
        oddsTypeElement.removeAttr('id');
        oddsTypeElement.removeClass('hidden');
        
        
        oddsData.find('type').each(function() {
        if ($(this).attr('value')=='3Way Result')
		        writeOddType3wayresult(marchid, oddsTypeElement, $(this));
        });

        // console.log(oddsTypeElement.children('div'));
        oddsElement.append(oddsTypeElement);
    }

    function writeOddType3wayresult(marchid, oddsTypeElement, oddsData) {
    	// console.log(oddsData);
    	oddType3wayresultElement = oddsTypeElement.children('div');
    	// associo un id univoco all'href
        oddType3wayresultElement.find('li.3wayresult').children('a').attr('id','3wayresult'+marchid);
        oddType3wayresultElementContent = oddType3wayresultElement.children('div').find('div.3wayresult');
        oddType3wayresultElementContent.attr('id','3wayresult'+marchid);
        
        oddsTableElement = $('#odd-3wayresult-table-template').clone();
        oddsTableElement.removeAttr('id');
        oddsTableElement.removeClass('hidden');
        
        oddsData.find('bookmaker').each(function() {
			writeBookmakerOddType3wayresult(marchid, oddsTableElement, $(this));
        });

        oddType3wayresultElementContent.append(oddsTableElement);
        
    }
    
    function writeBookmakerOddType3wayresult(marchid, oddsTableElement, bookmakerOdds) {

        oddRowElement = $('#odd-3wayresult-row-template').clone();
        oddRowElement.removeAttr('id');
        oddRowElement.removeClass('hidden');
        oddRowElement.find('td.bookmaker-name').html(bookmakerOdds.attr('name'));
        bookmakerOdds.find('odd').each(function() {
        	// console.log($(this).attr('value'));
	        oddRowElement.find('td.bookmaker-odd-'+$(this).attr('name')).html($(this).attr('value'));
        });
        // console.log(oddsTableElement);
        // console.log(oddRowElement);
        oddsTableElement.children('tbody').append(oddRowElement);
    }
    
</script>